# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
from .items import *


class CutMoviePipeline(object):
    # 定义MySQL连接
    def __init__(self):
        self.conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='test',
                                    charset='utf8')
        self.cursor = self.conn.cursor()

    # 处理管道信息进数据库
    def process_item(self, item, spider):

        if isinstance(item, CutMovieItem):  # 电影详细信息处理
            sql = "insert into t_movies(mid, movie_name, score, directors, actors, type, country, release_date, url, information) " \
                  "values(%s, %s, '%s', '%s', %s, '%s', '%s', '%s', '%s', %s)" % \
                  (item['mid'], repr(item['title']), item['rate'], item['directors'], repr(item['actors']),
                   item['types'], item['region'], item['release_year'], item['img_url'], repr(item['intro']))
        elif isinstance(item, LinesItem):  # 电影台词处理
            sql = "insert into t_lines(movie_id, line) values('%s', %s)" % (item['mid'], repr(item['line']))
        elif isinstance(item, ImageItem):  # 电影图片处理
            sql = "insert into t_picture(movie_id, url) values('%s', '%s')" % (item['mid'], item['img_url'])
        else:  # 电影类别处理
            sql = "insert into t_target(movie_id, target) values('%s', '%s')" % (item['mid'], item['name'])

        # 将正确数据添加至数据库
        try:
            self.cursor.execute(sql)
            self.conn.commit()
        except:
            print(sql)

        return item
